import os

import requests
from lxml import etree

# 下载4k美女图片
if __name__ == "__main__":
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36',
    }
    url = "http://pic.netbian.com/4kmeinv/index_2.html"
    page_text = requests.get(url=url, headers=headers).text
    # 解决中文乱码
    page_text = page_text.encode('iso-8859-1').decode('gbk')

    tree = etree.HTML(page_text)
    li_list = tree.xpath('//div[@class="slist"]/ul/li')
    baseUrl = 'http://pic.netbian.com'

    # 创建图片文件夹
    imp_dl_path = "./meinv_pic"
    if not os.path.exists(imp_dl_path):
        os.mkdir(imp_dl_path)

    for li in li_list:
        img_url = baseUrl + li.xpath('./a/img/@src')[0]
        img_name = li.xpath('./a/b/text()')[0] + ".jpg"
        print(img_url, img_name)

        img_r = requests.get(url=img_url, headers=headers)
        print(img_url + " " + str(img_r.status_code))
        # requests的content表示HTTP响应的二进制数据内容，即图片数据
        img_data = img_r.content

        img_path = "meinv_pic/" + img_name
        # 将图片数据写入文件
        with open(img_path, 'wb') as fp:
            fp.write(img_data)
            print(img_name + " download ok")
